﻿
#region Using Directives.

using System;
using System.Collections.Specialized;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Resources;
using System.Text;
using System.Windows.Forms;
using System.Xml.Linq;
using ActiproSoftware.SyntaxEditor;
using ActiproSoftware.SyntaxEditor.Commands;
using RWXMLEdit.Client.Forms;
using RWXMLEdit.Common;
using RWXMLEdit.UserControls;
using TD.SandDock;
using TD.SandDock.Rendering;

#endregion

namespace RWXMLEdit.Client
{
    public partial class FormRwXmlEditor : Form
    {
        #region Fields.
       
        private readonly string _winName = string.Format("{0} {1}", Application.ProductName, Application.ProductVersion);
        private const string MsgBoxName = "RailWorks XML Editor Message";
        private ResourceManager _resourceManager;
        private const string StartComment = "<!--";
        private const string EndComment = "-->";
        protected MruStripMenu MruMenu;
        private XDocument _xDocument;
        private XDeclaration _xDeclaration;
        private FormFindReplace _findReplaceForm;
        private readonly FindReplaceOptions _findReplaceOptions = new FindReplaceOptions();
        private const string Railworkspath = "<Click to set path>";
        private string _railWorksPath = Railworkspath;
        //private XDeclaration _declaration = new XDeclaration("1.0", "utf-8", "no");

        private SyntaxEditorEx _currentEditorEx;

        #endregion

        #region Constructor.

        public FormRwXmlEditor()
        {
            InitializeComponent();

            MruMenu = new MruStripMenu(recentFileMenuItem, OnMruFile, 16);
            
            RendererBase rb = new WhidbeyRenderer(); //EverettRenderer();

            sandDockManager.Renderer = rb;

            if(Properties.Settings.Default.LastOpenedFiles == null)
            {
                Properties.Settings.Default.LastOpenedFiles = new StringCollection();
            }
        }

        #endregion

        #region Form Events.

        private void sandDockManager_DockControlClosing(object sender, DockControlClosingEventArgs e)
        {
            bool isClosed = false;

            if (_currentEditorEx.Document.Modified)
            {
                string message = string.Format("There are some changes made to the current document, would you like to save changes to the file {0}?", _currentEditorEx.ExtendedInfo.Path);

                var r = MessageBox.Show(this, message, MsgBoxName, MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);

                SetWaitCursor(true);

                if (r == DialogResult.Yes)
                {
                    if (SaveXmlFile())
                    {
                        isClosed = true;
                    }
                }
                else if (r == DialogResult.No)
                {
                    isClosed = true;
                }
                else
                {
                    e.Cancel = true;
                }
            }
            else
            {
                SetWaitCursor(true);
                isClosed = true;
            }

            if (isClosed)
            {
                if(sandDockManager.GetDockControls().Length == 1)
                {
                    _currentEditorEx = null;

                    SetCloseStatus(false);

                    ResetEditor();

                    ResetStatusbar();

                    SetEditorFileInfo(string.Empty);

                    EnableDisableToolBar(false);

                    EnableDisableMenu(false);
                }
            }

            SetWaitCursor(false);
        }

        private void sandDockManager_ActiveTabbedDocumentChanged(object sender, EventArgs e)
        {
            if (_currentEditorEx != null)
                DisconnectSyntaxEditor();

            if(sandDockManager.ActiveTabbedDocument != null)
            {
                _currentEditorEx = (SyntaxEditorEx)sandDockManager.ActiveTabbedDocument.Controls[0];
                                 
                ConnectNewSyntaxEditor();

                Text = string.Format("{1} - {0}", _winName, _currentEditorEx.ExtendedInfo.Path);

                if (_findReplaceForm != null)
                    _findReplaceForm.SyntaxEditor = _currentEditorEx;

                EnableDisableToolBar(true);

                EnableDisableMenu(true);

                if (Functions.IsFileReadOnly(_currentEditorEx.ExtendedInfo.Path))
                {
                    SetDocumentSaveStatus(_currentEditorEx.Document.Modified);

                    _currentEditorEx.Document.ReadOnly = true;

                    SetSaveStatus(false);

                    sandDockManager.ActiveTabbedDocument.TabImage = imlTabs.Images[2];
                }
                else
                {
                    SetDocumentSaveStatus(_currentEditorEx.Document.Modified);

                    _currentEditorEx.Document.ReadOnly = false;

                    SetSaveStatus(_currentEditorEx.Document.Modified);
                }

                SetDocumentInfo(_currentEditorEx.Document.Length, _currentEditorEx.Document.Lines.Count);

                DocumentPosition pos = _currentEditorEx.Caret.DisplayDocumentPosition;

                int position = _currentEditorEx.Caret.Offset;

                SetPositionInfo(pos.Line, pos.Character, position);

                SetSelectionInfo(_currentEditorEx.SelectedView.Selection.Length);

                SetCloseStatus(true);

                SetEditorFileInfo(_currentEditorEx.ExtendedInfo.Path);

                RefreshUndoRedoStatus(_currentEditorEx.Document.UndoRedo.CanUndo, _currentEditorEx.Document.UndoRedo.CanRedo);
            }
        }

        private void OnMruFile(int number, String filename)
        {
            if(File.Exists(filename))
            {
                OpenXmlFile(filename);
            }
            else
            {
                string message = string.Format("The file: {0} can not be opened and will be removed from the Recent list(s)", filename);

                MessageBox.Show(this, message, MsgBoxName, MessageBoxButtons.OK, MessageBoxIcon.Error);

                MruMenu.RemoveFile(number);

                if (MruMenu.MenuItems.Count == 0)
                    recentFileMenuItem.Enabled = false;
            }
        }

        private void FormEditor_Load(object sender, EventArgs e)
        {
            InitForm();

            string fileList = Properties.Settings.Default.MruFileList;

            StringCollection lastOpenedFiles = Properties.Settings.Default.LastOpenedFiles;

            _railWorksPath = Properties.Settings.Default.RailWorksPath;

            if(!string.IsNullOrEmpty(_railWorksPath) && Directory.Exists(_railWorksPath))
            {
                llbRailWorksPath.Links[0].LinkData = _railWorksPath;

                llbRailWorksPath.Text = _railWorksPath; 
            }
            else
            {
                llbRailWorksPath.Text = Railworkspath;
            }

            mnuMain.ImageList = imlMenu;
            tlbMain.ImageList = imlMenu;

            if(!string.IsNullOrEmpty(fileList))
            {
                MruMenu.LoadFromString(fileList);
                recentFileMenuItem.Enabled = true;
            }

            if (lastOpenedFiles.Count > 0)
            {
                foreach (string lastOpenedFile in lastOpenedFiles)
                {
                    if (File.Exists(lastOpenedFile))
                    {
                        OpenXmlFile(lastOpenedFile);
                    }   
                }
            }
        }

        private void FormEditor_FormClosing(object sender, FormClosingEventArgs e)
        {
            Properties.Settings.Default.LastOpenedFiles.Clear();

            Properties.Settings.Default.MruFileList = MruMenu.SaveToString();

            if(sandDockManager.GetDockControls().Length < 1)
            {
                Properties.Settings.Default.Save();
                return;
            }

            sandDockManager.DockControlClosing -= sandDockManager_DockControlClosing;

            bool isClosed = false;

            foreach (DockControl c in sandDockManager.GetDockControls())
            {
                _currentEditorEx = (SyntaxEditorEx)c.Controls[0];

                if (_currentEditorEx.Document.Modified && !Functions.IsFileReadOnly(_currentEditorEx.ExtendedInfo.Path))
                {
                    string message = string.Format("There are some changes made to the current document, would you like to save changes to the file {0}?", _currentEditorEx.ExtendedInfo.Path);
                        
                    var r = MessageBox.Show(this, message , MsgBoxName, MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);

                    SetWaitCursor(true);

                    if (r == DialogResult.Yes)
                    {
                        if (SaveXmlFile())
                        {
                            isClosed = true;
                        }
                        else
                        {
                            e.Cancel = true;
                            break;
                        }
                    }
                    else if (r == DialogResult.No)
                    {
                        isClosed = true;
                    }
                    else
                    {
                        e.Cancel = true;
                        break;
                    }
                }
                else
                {
                    SetWaitCursor(true);
                    isClosed = true;
                }

                if (isClosed)
                {
                    Properties.Settings.Default.LastOpenedFiles.Add(_currentEditorEx.ExtendedInfo.Path);

                    c.CloseAction = DockControlCloseAction.Dispose;

                    c.Close();

                    if (sandDockManager.GetDockControls().Length == 0)
                    {
                        _currentEditorEx = null;

                        SetCloseStatus(false);

                        ResetEditor();

                        ResetStatusbar();

                        SetEditorFileInfo(string.Empty);

                        EnableDisableToolBar(false);

                        EnableDisableMenu(false);
                    }
                }

                Properties.Settings.Default.Save();

                SetWaitCursor(false);
            }
        }

        private void FormEditor_Activated(object sender, EventArgs e)
        {
            HasClipboardText();

            if(tmrCheckFiles.Enabled == false)
            {
                tmrCheckFiles.Enabled = true;
            }
        }

        private void FormRwXmlEditor_Deactivate(object sender, EventArgs e)
        {
            tmrCheckFiles.Enabled = false;
        }

        private void tmrCheckFiles_Tick(object sender, EventArgs e)
        {
            if (_currentEditorEx != null && sandDockManager.GetDockControls().Length > 0)
            {
                CheckForChanges();
                tmrCheckFiles.Enabled = false;
            }
        }

        private void CheckForChanges()
        {
            foreach(DockControl dc in sandDockManager.GetDockControls())
            {
                SyntaxEditorEx editor = (SyntaxEditorEx) dc.Controls[0];

                FileInfoTypes fileInfoTypes = Functions.CheckFileStatus(editor.ExtendedInfo.Path, editor.ExtendedInfo.Md5CheckSum);
                                                                        
                if(fileInfoTypes == FileInfoTypes.FileIsMissing)
                {
                    string message = string.Format("The file \"{0}\" does not exist anymore.\n\nKeep this file in editor", editor.ExtendedInfo.Path);

                    DialogResult dialogResult = MessageBox.Show(this, message, MsgBoxName, MessageBoxButtons.YesNo, MessageBoxIcon.Question);

                    if(dialogResult == DialogResult.No)
                    {
                        editor.Document.Modified = false;
                        
                        dc.CloseAction = DockControlCloseAction.Dispose;

                        dc.Close();
                    }
                    else
                    {
                        if(sandDockManager.ActiveTabbedDocument == dc)
                        {
                            _currentEditorEx.ExtendedInfo.Md5CheckSum = string.Empty;

                            _currentEditorEx.Document.Modified = true;

                            SetDocumentSaveStatus(_currentEditorEx.Document.Modified);

                            SetSaveStatus(_currentEditorEx.Document.Modified);
                        }
                        else
                        {
                            editor.ExtendedInfo.Md5CheckSum = string.Empty;
                            
                            editor.Document.Modified = true;

                            dc.TabImage = imlTabs.Images[1];
                        }
                    }
                }
                
                if(fileInfoTypes == FileInfoTypes.FileIsChanged)
                {
                    string message = string.Format("{0}\n\nThis file has been modified by another program.\n\nDo you want to reload it?", editor.ExtendedInfo.Path);

                    DialogResult dialogResult = MessageBox.Show(this, message, MsgBoxName, MessageBoxButtons.YesNo, MessageBoxIcon.Question);

                    if (dialogResult == DialogResult.Yes)
                    {
                        _currentEditorEx.DocumentTextChanged -= (OnDocumentTextChanged);

                        if (sandDockManager.ActiveTabbedDocument == dc)
                        {
                            _currentEditorEx.Document.LoadFile(_currentEditorEx.ExtendedInfo.Path);

                            _currentEditorEx.ExtendedInfo.Md5CheckSum = RwHasher.GetMd5Hash(_currentEditorEx.ExtendedInfo.Path);

                            _currentEditorEx.Document.Modified = false;
                        }
                        else
                        {
                            editor.Document.LoadFile(editor.ExtendedInfo.Path);

                            editor.ExtendedInfo.Md5CheckSum = RwHasher.GetMd5Hash(editor.ExtendedInfo.Path);

                            editor.Document.Modified = false;
                        }

                        _currentEditorEx.DocumentTextChanged += (OnDocumentTextChanged);
                    }
                    else
                    {
                        editor.ExtendedInfo.Md5CheckSum = string.Empty;
                    }
                }

                if(fileInfoTypes == FileInfoTypes.FileIsWriteProtected)
                {
                    if (sandDockManager.ActiveTabbedDocument == dc)
                    {
                        SetSaveStatus(false);

                        dc.TabImage = imlTabs.Images[2];
                    }
                    else
                    {
                        dc.TabImage = imlTabs.Images[2];
                    }
                }

                if(fileInfoTypes == FileInfoTypes.FileIsOk)
                {
                    if (((SyntaxEditor)dc.Controls[0]).Document.ReadOnly)
                        ((SyntaxEditor) dc.Controls[0]).Document.ReadOnly = false;

                    if(editor.Document.Modified)
                    {
                        dc.TabImage = imlTabs.Images[1];
                    }
                    else
                    {
                        dc.TabImage = imlTabs.Images[0];
                    }
                }
            }
        }

        private void llbRailWorksPath_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {

            }
            else
            {
                if (_railWorksPath == Railworkspath)
                {
                    SetRailWorksPath();
                }
                else
                {
                    var path = e.Link.LinkData as string;

                    if (!string.IsNullOrEmpty(path) && Directory.Exists(path))
                    {
                        System.Diagnostics.Process.Start(path);
                    }
                    else
                    {
                        string message = string.Format("Could not open the path:\n\n [{0}]", path);

                        MessageBox.Show(this, message, MsgBoxName, MessageBoxButtons.OK, MessageBoxIcon.Warning);

                        llbRailWorksPath.Text = Railworkspath;
                    }
                }
            }
        }

        #endregion

        #region File Menu And Toolbar Methods.

        #region OpenXMLFile.

        private void OpenXmlFile(string path)
        {
            SetWaitCursor(true);

            SyntaxEditorEx syntaxEditor = new SyntaxEditorEx();

            Document doc = new Document();

            string xmlFilePath = path;

            string xmlBackupPath = string.Empty;

            string xmlFileName = string.Empty;

            string md5CheckSum = string.Empty;

            try
            {
                _xDocument = XDocument.Load(xmlFilePath, LoadOptions.PreserveWhitespace);

                _xDeclaration = _xDocument.Declaration;

                doc.Text = _xDocument.ToString();

                doc.InsertText(DocumentModificationType.Custom, 0, _xDeclaration.ToString());

                //Save a backup of the file
                string personalFolder = Functions.GetPersonalFolder();

                md5CheckSum = RwHasher.GetMd5Hash(xmlFilePath);

                xmlFileName = Path.GetFileName(xmlFilePath);

                xmlBackupPath = string.Format("{0}\\{1}.bak", personalFolder, xmlFileName);

                doc.SaveFile(xmlBackupPath, Encoding.UTF8, LineTerminator.CarriageReturnNewline);

                fileSystemWatcher.Path = Path.GetDirectoryName(xmlFilePath);

                fileSystemWatcher.EnableRaisingEvents = true;

                MruMenu.AddFile(xmlFilePath);

                Assembly assembly = Assembly.GetExecutingAssembly();

                Stream stream = assembly.GetManifestResourceStream("RWXMLEdit.Client.RWXMLEdit.XML.xml");

                doc.LoadLanguageFromXml(stream, 0);

                doc.Outlining.Mode = OutliningMode.Automatic;

                doc.LineModificationMarkingEnabled = true;

                doc.SemanticParsingEnabled = true;

                doc.LexicalParsingEnabled = true;

                syntaxEditor.DefaultContextMenuEnabled = false;

                syntaxEditor.LineNumberMarginVisible = true;

                syntaxEditor.ContextMenuStrip = textAreaContextMenu;

                syntaxEditor.Document = doc;

                syntaxEditor.Document.Modified = false;
                
                InitNewSyntaxEditor(syntaxEditor);

                EditorInfoEx editorInfo = new EditorInfoEx(xmlFilePath, xmlBackupPath, xmlFileName, md5CheckSum);

                syntaxEditor.ExtendedInfo = editorInfo;

                DockControl window = new TabbedDocument(sandDockManager, syntaxEditor, xmlFileName);

                window.ToolTipText = editorInfo.Path;

                window.TabImage = imlTabs.Images[0];

                if (Functions.IsFileReadOnly(xmlFilePath))
                {
                    statusLabelPath.ForeColor = Color.Red;
                    window.TabImage = imlTabs.Images[2];
                }
                else
                {
                    statusLabelPath.ForeColor = Color.DarkGreen;
                    window.TabImage = imlTabs.Images[0];
                }

                Text = string.Format("{1} - {0}", _winName, xmlFilePath);
                
                SetSaveStatus(false);

                SetDocumentInfo(syntaxEditor.Document.Length, syntaxEditor.Document.Lines.Count);

                SetPositionInfo(1, 1, 0);

                SetSelectionInfo(0);

                SetEditorFileInfo(xmlFilePath);

                window.Open();
            }
            catch (Exception)
            {
                const string message = "The selected XML-file could not be opened for edit!";

                MessageBox.Show(this, message, MsgBoxName, MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            finally
            {
                SetWaitCursor(false);
            }
        }

        private void OpenXmlFile()
        {
            //string startPath = Path.Combine(_railWorksPath, "Source");

            openFileDialog.Title = @"Open XML File For Edit";
            openFileDialog.ReadOnlyChecked = false;
            openFileDialog.Multiselect = true;
            openFileDialog.InitialDirectory = !string.IsNullOrEmpty(_railWorksPath) ? _railWorksPath : Properties.Settings.Default.LastOpenedFilePath;

            DialogResult open = openFileDialog.ShowDialog(this);

            if (open == DialogResult.OK)
            {
                if(openFileDialog.FileNames.Length > 1)
                {
                    foreach (string path in openFileDialog.FileNames)
                    {
                        if (!IsFileOpened(path))
                        {
                            OpenXmlFile(path);
                        }
                    }
                }
                else
                {
                    if(!IsFileOpened(openFileDialog.FileName))
                        OpenXmlFile(openFileDialog.FileName);
                }
            }
        }

        #endregion

        #region SaveXMLFile.

        private bool SaveXmlFile()
        {
            SetWaitCursor(true);

            try
            {
                if (_currentEditorEx.Document.Modified)
                {
                    _currentEditorEx.Document.SaveFile(_currentEditorEx.ExtendedInfo.Path, Encoding.UTF8, LineTerminator.CarriageReturnNewline);

                    _currentEditorEx.ExtendedInfo.Md5CheckSum = RwHasher.GetMd5Hash(_currentEditorEx.ExtendedInfo.Path);

                    _currentEditorEx.Document.Modified = false;

                    SetDocumentSaveStatus(false);

                    SetSaveStatus(false);
                }

                return true;
            }
            catch (Exception ex)
            {
                string message = string.Format("There was a problem saving changes to the XML-file [{0}]\n\n{1}", _currentEditorEx.ExtendedInfo.FileName, ex.Message);

                MessageBox.Show(this, message, MsgBoxName, MessageBoxButtons.OK, MessageBoxIcon.Error);

                return false;
            }
            finally
            {
                SetWaitCursor(false);
            }
        }

        private bool SaveAllXmlFiles()
        {
            bool retval = true;

            foreach (DockControl c in sandDockManager.GetDockControls())
            {
                _currentEditorEx = (SyntaxEditorEx)c.Controls[0];

                if (_currentEditorEx.Document.Modified)
                {
                    retval = SaveXmlFile();

                    if(retval)
                    {
                        c.TabImage = imlTabs.Images[0];
                    }
                }
            }

            _currentEditorEx = (SyntaxEditorEx)sandDockManager.ActiveTabbedDocument.Controls[0];

            return retval;
        }

        #endregion

        #region SaveXMLFileAs.

        private void SaveXmlFileAs()
        {
            if (string.IsNullOrEmpty(_currentEditorEx.ExtendedInfo.Path))
            {
                const string message = "There is no XML-file open to save!";

                MessageBox.Show(this, message, MsgBoxName, MessageBoxButtons.OK, MessageBoxIcon.Warning);

                return;
            }

            saveFileDialog.InitialDirectory = _currentEditorEx.ExtendedInfo.Path;
            saveFileDialog.FileName = _currentEditorEx.ExtendedInfo.FileName;
            saveFileDialog.Title = @"Save XML File As";

            DialogResult save = saveFileDialog.ShowDialog(this);

            if (save == DialogResult.OK)
            {
                SetWaitCursor(true);

                try
                {
                    string saveAsFilePath = saveFileDialog.FileName;

                    _currentEditorEx.Document.SaveFile(saveAsFilePath, Encoding.UTF8, LineTerminator.CarriageReturnNewline);

                    _currentEditorEx.ExtendedInfo.Path = saveAsFilePath;

                    _currentEditorEx.ExtendedInfo.FileName = Path.GetFileName(_currentEditorEx.ExtendedInfo.Path);

                    _currentEditorEx.ExtendedInfo.Md5CheckSum = RwHasher.GetMd5Hash(_currentEditorEx.ExtendedInfo.Path);

                    MruMenu.AddFile(_currentEditorEx.ExtendedInfo.Path);

                    _currentEditorEx.Document.Modified = false;

                    SetDocumentSaveStatus(false);

                    SetSaveStatus(false);

                    SetEditorFileInfo(_currentEditorEx.ExtendedInfo.Path);

                    sandDockManager.ActiveTabbedDocument.TabText = _currentEditorEx.ExtendedInfo.FileName;
                }
                catch (Exception)
                {
                    string message = string.Format("There was a problem saving XML-file to [{0}]", saveFileDialog.FileName);
                    MessageBox.Show(this, message, MsgBoxName, MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                finally
                {
                    SetWaitCursor(false);
                }
            }
        }

        #endregion

        #region ExportXMLFile.

        private void SaveAsHtml()
        {
            if (string.IsNullOrEmpty(_currentEditorEx.ExtendedInfo.Path))
            {
                const string message = "There is no XML-file open for export to HTML";

                MessageBox.Show(this, message, MsgBoxName, MessageBoxButtons.OK, MessageBoxIcon.Warning);

                return;
            }

            saveFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
            saveFileDialog.Title = @"Save XML File As HTML";
            saveFileDialog.Filter = @"Web Page|*.htm;*.html";
            saveFileDialog.DefaultExt = "htm";

            DialogResult save = saveFileDialog.ShowDialog(this);

            if (save == DialogResult.OK)
            {
                string filename = saveFileDialog.FileName;

                string title = string.Format("RailWorks XML Edit - {0}", _currentEditorEx.ExtendedInfo.FileName);

                try
                {
                    _currentEditorEx.Document.SaveFileAsHtml(filename, HtmlExportType.Inline, LineTerminator.CarriageReturnNewline, title);

                    System.Diagnostics.Process.Start(filename);
                }
                catch (Exception ex)
                {
                    string message = string.Format("There was an error exporting to HTML\n\n{0}", ex.Message);

                    MessageBox.Show(this, message, MsgBoxName, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            }
        }

        private void SaveAsRtf()
        {
            if (string.IsNullOrEmpty(_currentEditorEx.ExtendedInfo.Path))
            {
                const string message = "There is no XML-file open for export to RTF";

                MessageBox.Show(this, message, MsgBoxName, MessageBoxButtons.OK, MessageBoxIcon.Warning);

                return;
            }

            saveFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
            saveFileDialog.Title = @"Save XML File As Rich Text Format";
            saveFileDialog.Filter = @"Rich Text Format|*.rtf";
            saveFileDialog.DefaultExt = "rtf";

            DialogResult save = saveFileDialog.ShowDialog(this);

            if (save == DialogResult.OK)
            {
                string filename = saveFileDialog.FileName;

                try
                {
                    _currentEditorEx.Document.SaveFileAsRtf(filename, _currentEditorEx.Font, LineTerminator.CarriageReturnNewline);

                    System.Diagnostics.Process.Start(filename);
                }
                catch (Exception ex)
                {
                    string message = string.Format("There was an error exporting to RTF\n\n{0}", ex.Message);

                    MessageBox.Show(this, message, MsgBoxName, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            }
        }

        #endregion

        #region CloseXMLFile.

        private void CloseXmlFile()
        {
            sandDockManager.ActiveTabbedDocument.CloseAction = DockControlCloseAction.Dispose;

            sandDockManager.ActiveTabbedDocument.Close();
        }

        private void CloseAllXmlFiles(bool leaveCurrent)
        {
            sandDockManager.DockControlClosing -= sandDockManager_DockControlClosing;

            SyntaxEditorEx backup = null;

            Guid current = sandDockManager.ActiveTabbedDocument.Guid;
            
            bool isClosed = false;

            foreach (DockControl dc in sandDockManager.GetDockControls())
            {
                 _currentEditorEx = (SyntaxEditorEx)dc.Controls[0];

                if(dc.Guid == current && leaveCurrent)
                {
                    backup = _currentEditorEx;
                    isClosed = false;
                }
                else if (_currentEditorEx.Document.Modified)
                {
                    string message = string.Format("There are some changes made to the current document, would you like to save changes to the file {0}?", _currentEditorEx.ExtendedInfo.Path);

                    var r = MessageBox.Show(this, message, MsgBoxName, MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);

                    SetWaitCursor(true);

                    if (r == DialogResult.Yes)
                    {
                        if (SaveXmlFile())
                        {
                            isClosed = true;
                        }
                    }
                    else if (r == DialogResult.No)
                    {
                        isClosed = true;
                    }
                    else
                    {
                        break;
                    }
                }
                else
                {
                    SetWaitCursor(true);
                    isClosed = true;
                }

                if (isClosed)
                {
                    dc.CloseAction = DockControlCloseAction.Dispose;

                    dc.Close();

                    if (sandDockManager.GetDockControls().Length == 0)
                    {
                        _currentEditorEx = null;

                        SetCloseStatus(false);

                        ResetEditor();

                        ResetStatusbar();

                        SetEditorFileInfo(string.Empty);

                        EnableDisableToolBar(false);

                        EnableDisableMenu(false);
                    }
                }
                else
                {
                    //if (backup != null) 
                        
                }

                SetWaitCursor(false);
            }

            if(backup != null && sandDockManager.ActiveTabbedDocument.Guid == current)
            {
                _currentEditorEx = backup;
            }

            sandDockManager.DockControlClosing += sandDockManager_DockControlClosing;
        }

        #endregion

        #region BackupXMLFile.

        private void BackupXmlFile()
        {
            if (!string.IsNullOrEmpty(_currentEditorEx.ExtendedInfo.BackupPath))
            {
                saveFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
                saveFileDialog.Title = @"Backup Original RW XML File To";

                string fileName = Path.GetFileNameWithoutExtension(_currentEditorEx.ExtendedInfo.BackupPath);

                string backupDatePart = string.Format("{0}{1:0#}{2:0#}", DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day);

                string backupTimePart = string.Format("{0:0#}{1:0#}{2:0#}", DateTime.Now.Hour, DateTime.Now.Minute, DateTime.Now.Second);

                saveFileDialog.FileName = string.Format("{0}_{1}_{2}.xml", fileName, backupDatePart, backupTimePart);

                DialogResult save = saveFileDialog.ShowDialog(this);

                SetWaitCursor(true);

                if (save == DialogResult.OK)
                {
                    try
                    {
                        FileInfo fi = new FileInfo(_currentEditorEx.ExtendedInfo.BackupPath);

                        fi.CopyTo(saveFileDialog.FileName);

                        string message = string.Format("Created a backup of the original XML-file to:\n\n [{0}]", saveFileDialog.FileName);

                        MessageBox.Show(this, message, MsgBoxName, MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                    catch (Exception)
                    {
                        string message = string.Format("Could not created a backup of the original XML-file to:\n\n [{0}]", saveFileDialog.FileName);

                        MessageBox.Show(this, message, MsgBoxName, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    }
                    finally
                    {
                        SetWaitCursor(false);
                    }
                }
            }
        }

        #endregion

        #region PrintXMLFile.

        private void PrintNow()
        {
            if (!_currentEditorEx.Document.HasContent)
            {
                return;
            }

            string docName = GetPrintingDocumentName(_currentEditorEx.ExtendedInfo.FileName);
            string date = DateTime.Now.ToShortDateString();
            string time = DateTime.Now.ToShortTimeString();

            _currentEditorEx.PrintSettings.PrintDocument.DocumentName = docName;
            _currentEditorEx.PrintSettings.DocumentTitle = string.Format("Utskrift av filen [{0}] {1} {2}", _currentEditorEx.ExtendedInfo.FileName, date, time);
            _currentEditorEx.Print(false);
        }

        private void Print()
        {
            if (!_currentEditorEx.Document.HasContent)
            {
                return;
            }

            string docName = GetPrintingDocumentName(_currentEditorEx.ExtendedInfo.FileName);

            _currentEditorEx.PrintSettings.PrintDocument.DocumentName = docName;

            printDialog.Document = _currentEditorEx.PrintSettings.PrintDocument;

            printDialog.AllowSelection = true;

            printDialog.AllowSomePages = true;

            DialogResult print = printDialog.ShowDialog(this);

            if (print == DialogResult.OK)
            {
                string date = DateTime.Now.ToShortDateString();
                string time = DateTime.Now.ToShortTimeString();

                _currentEditorEx.PrintSettings.DocumentTitle = string.Format("Utskrift av filen [{0}] {1} {2}", _currentEditorEx.ExtendedInfo.FileName, date, time);
                _currentEditorEx.PrintSettings.PrintDocument.PrinterSettings = printDialog.PrinterSettings;
                _currentEditorEx.PrintSettings.PrintDocument.Print();
            }
        }

        private void PrintPreview()
        {
            if (_currentEditorEx == null)
            {
                return;
            }

            if (!_currentEditorEx.Document.HasContent)
            {
                return;
            }

            string docName = GetPrintingDocumentName(_currentEditorEx.ExtendedInfo.FileName);

            var s = new Size(1200, 900);
            var bitmap = (Bitmap)_resourceManager.GetObject("PrintPreviewHS");

            printPreviewDialog.Size = s;
            printPreviewDialog.StartPosition = FormStartPosition.CenterScreen;
            printPreviewDialog.PrintPreviewControl.Zoom = 1.0;
            printPreviewDialog.Text = String.Format("Preview {0}", docName);

            if (bitmap != null)
            {
                printPreviewDialog.Icon = Icon.FromHandle(bitmap.GetHicon());
            }

            string date = DateTime.Now.ToShortDateString();
            string time = DateTime.Now.ToShortTimeString();

            _currentEditorEx.PrintSettings.DocumentTitle = string.Format("Utskrift av filen [{0}] {1} {2}", _currentEditorEx.ExtendedInfo.FileName, date, time);

            printPreviewDialog.Document = _currentEditorEx.PrintSettings.PrintDocument;
            printPreviewDialog.Document.DocumentName = docName;
            printPreviewDialog.ShowDialog(this);
        }

        private void PageSetup()
        {
            _currentEditorEx.ShowPageSetupForm(this);
        }

        #endregion

        #endregion

        #region Edit Menu And Toolbar Methods.

        private void Undo()
        {
            _currentEditorEx.Document.UndoRedo.Undo();
        }

        private void Redo()
        {
            _currentEditorEx.Document.UndoRedo.Redo();
        }

        private void Cut()
        {
            if (!_currentEditorEx.Document.HasContent)
                return;

            _currentEditorEx.SelectedView.CutToClipboard();
            HasClipboardText();
        }

        private void Copy()
        {
            if (!_currentEditorEx.Document.HasContent)
                return;

            _currentEditorEx.SelectedView.CopyToClipboard();
            HasClipboardText();
        }

        private void Paste()
        {
            if (_currentEditorEx.Enabled)
            {
                _currentEditorEx.SelectedView.PasteFromClipboard();
            }
        }

        private void CutAndAppend()
        {
            _currentEditorEx.SelectedView.CutAndAppendToClipboard();
        }

        private void CopyAndAppend()
        {
            _currentEditorEx.SelectedView.CopyAndAppendToClipboard();
        }

        private void ClearClipboard()
        {
            if (Clipboard.ContainsText(TextDataFormat.UnicodeText) || Clipboard.ContainsText(TextDataFormat.Text))
            {
                Clipboard.Clear();
                HasClipboardText();
            }
        }

        private void Delete()
        {
            _currentEditorEx.SelectedView.Delete();
        }

        private void SelectAll()
        {
            _currentEditorEx.SelectedView.Selection.SelectAll();
        }

        private void SelectLine()
        {
            _currentEditorEx.SelectedView.Selection.MoveToLineStart();
            _currentEditorEx.SelectedView.Selection.SelectToLineEnd();
        }

        private void SelectWord()
        {
            _currentEditorEx.SelectedView.Selection.SelectWord();
        }

        private void SelectNone()
        {
            int offset = _currentEditorEx.SelectedView.Selection.FirstOffset;
            _currentEditorEx.SelectedView.Selection.SelectRange(offset, 0);
        }

        private void ToggleBookmark()
        {
            if (_currentEditorEx.SelectedView.CurrentDocumentLine.LineIndicators.Contains(BookmarkLineIndicator.DefaultName))
            {
                _currentEditorEx.SelectedView.CurrentDocumentLine.LineIndicators.Clear(BookmarkLineIndicator.DefaultName);
            }
            else
            {
                _currentEditorEx.Document.LineIndicators.Add(new BookmarkLineIndicator(), _currentEditorEx.Caret.DocumentPosition.Line);
            }
        }

        private void EnableBookmark()
        {
            int index = _currentEditorEx.SelectedView.CurrentDocumentLine.LineIndicators.IndexOf(BookmarkLineIndicator.DefaultName);

            if (index != -1)
            {
                (_currentEditorEx.SelectedView.CurrentDocumentLine.LineIndicators[index]).CanNavigateTo =
                    !(_currentEditorEx.SelectedView.CurrentDocumentLine.LineIndicators[index]).CanNavigateTo;

                _currentEditorEx.Invalidate();
            }
        }

        private void EnableAllBookmarks()
        {
            DocumentLineCollection lines = _currentEditorEx.Document.Lines;

            foreach (DocumentLine line in lines)
            {
                int index = line.LineIndicators.IndexOf(BookmarkLineIndicator.DefaultName);

                if (index != -1 && line.LineIndicators[index].CanNavigateTo == false)
                {
                    line.LineIndicators[index].CanNavigateTo = true;
                }
            }

            _currentEditorEx.Invalidate();
        }

        private void GoToPreviousBookmark()
        {
            _currentEditorEx.SelectedView.GotoPreviousLineIndicator(BookmarkLineIndicator.DefaultName);
        }

        private void GoToNextBookmark()
        {
            _currentEditorEx.SelectedView.GotoNextLineIndicator(BookmarkLineIndicator.DefaultName);
        }

        private void ClearBookmarks()
        {
            const string message = "Are you sure that you want to clear all bookmarks?";

            DialogResult clearBookmarks = MessageBox.Show(this, message, MsgBoxName, MessageBoxButtons.YesNo, MessageBoxIcon.Question);

            if (clearBookmarks == DialogResult.Yes)
            {
                _currentEditorEx.Document.LineIndicators.Clear(BookmarkLineIndicator.DefaultName);
            }
        }

        private void CommentSelection()
        {
            if (!_currentEditorEx.Document.HasContent)
                return;

            if (!_currentEditorEx.SelectedView.SelectedText.StartsWith(StartComment) && !_currentEditorEx.SelectedView.SelectedText.EndsWith(EndComment))
            {
                int startLine = _currentEditorEx.SelectedView.Selection.StartDocumentPosition.Line;
                int endLine = _currentEditorEx.SelectedView.Selection.EndDocumentPosition.Line;
                int selLines = _currentEditorEx.SelectedView.Selection.DocumentPositionRange.Lines;
                int startSelection = startLine;

                if (startLine > endLine)
                    startSelection = endLine;

                int endSelection = startSelection + selLines - 1;

                int ws = _currentEditorEx.Document.Lines[startSelection].StartOffset + _currentEditorEx.Document.Lines[startSelection].TabStopLevel;

                TextRange range = new TextRange(ws, _currentEditorEx.Document.Lines[endSelection].EndOffset);

                _currentEditorEx.SelectedView.Selection.SelectRange(range);

                _currentEditorEx.SelectedView.InsertSurroundingText(DocumentModificationType.Typing, StartComment, EndComment);

                range = new TextRange(_currentEditorEx.Document.Lines[startSelection].StartOffset, _currentEditorEx.Document.Lines[endSelection].EndOffset);

                _currentEditorEx.SelectedView.Selection.SelectRange(range);
            }
        }

        private void UncommentSelection()
        {
            if (!_currentEditorEx.Document.HasContent)
                return;

            string startText = _currentEditorEx.SelectedView.SelectedText.Trim();

            if (startText.StartsWith(StartComment) && _currentEditorEx.SelectedView.SelectedText.EndsWith(EndComment))
            {
                int startLine = _currentEditorEx.SelectedView.Selection.StartDocumentPosition.Line;
                int endLine = _currentEditorEx.SelectedView.Selection.EndDocumentPosition.Line;
                int selLines = _currentEditorEx.SelectedView.Selection.DocumentPositionRange.Lines;

                int startSelection = startLine;

                if (startLine > endLine)
                    startSelection = endLine;

                int endSelection = startSelection + selLines - 1;

                StringBuilder sb = new StringBuilder(_currentEditorEx.SelectedView.SelectedText);

                sb.Replace(StartComment, string.Empty);

                sb.Replace(EndComment, string.Empty);

                _currentEditorEx.SelectedView.SelectedText = sb.ToString();

                TextRange range = new TextRange(_currentEditorEx.Document.Lines[startSelection].StartOffset,
                                                _currentEditorEx.Document.Lines[endSelection].EndOffset);

                _currentEditorEx.SelectedView.Selection.SelectRange(range);

            }
        }

        private void ShowFindAndReplace()
        {
            if (_findReplaceForm == null)
            {
                _findReplaceForm = new FormFindReplace(_currentEditorEx, _findReplaceOptions);
                //_findReplaceForm.StatusChanged += (findReplaceForm_StatusChanged);
            }

            _findReplaceForm.Owner = this;

            if (_findReplaceForm.Visible)
                _findReplaceForm.Activate();
            else
                _findReplaceForm.Show();
        }

        private void ShowGoTo()
        {
            if (_currentEditorEx.Document.HasContent)
            {
                FormGotoLine frm = new FormGotoLine(_currentEditorEx);

                frm.ShowDialog(this);
            }
        }

        #endregion

        #region Format Menu And Toolbar Methods.

        private void MakeUppercase()
        {
            _currentEditorEx.SelectedView.ChangeCharacterCasing(CharacterCasing.Upper);
        }

        private void MakeLowercase()
        {
            _currentEditorEx.SelectedView.ChangeCharacterCasing(CharacterCasing.Lower);
        }

        private void Capitalize()
        {
            _currentEditorEx.SelectedView.ChangeCharacterCasing(CharacterCasing.Lower);
            _currentEditorEx.SelectedView.ChangeCharacterCasing(CharacterCasing.Normal);
        }

        private void InvertCaseing()
        {
            _currentEditorEx.SelectedView.SelectedText = Functions.InvertCasing(_currentEditorEx.SelectedView.SelectedText);
        }

        private void IncreaseIndent()
        {
            _currentEditorEx.SelectedView.Indent();
        }

        private void DecreaseIndent()
        {
            _currentEditorEx.SelectedView.Outdent();
        }

        private void ConvertTabsToSpaces()
        {
            _currentEditorEx.SelectedView.ConvertTabsToSpaces();
        }

        private void ConvertSpacesToTabs()
        {
            _currentEditorEx.SelectedView.ConvertSpacesToTabs();
        }

        private void TabifySelection()
        {
            _currentEditorEx.SelectedView.TabifySelectedLines();
        }

        private void UntabifySelection()
        {
            _currentEditorEx.SelectedView.UntabifySelectedLines();
        }

        private void TrimTrailingWhitespace()
        {
            _currentEditorEx.SelectedView.TrimTrailingWhitespace();
        }

        #endregion

        #region View Menu And Toolbar Methods.
        
        private void viewShowColumn80GuideMenuItem_Click(object sender, EventArgs e)
        {
            ShowColumn80Guide();
        }
        
        private void ShowColumn80Guide()
        {
            _currentEditorEx.ColumnGuides.Clear();
            if (!viewShowColumn80GuideMenuItem.Checked)
            {
                _currentEditorEx.ColumnGuides.Add(new ColumnGuide(ColumnGuideValueType.Column, 80, SystemColors.ControlDark));
            }

            OnSettingsChanged();

            _currentEditorEx.Invalidate();
        }

        private void OnSettingsChanged()
        {
            viewShowSpacesTabsMenuItem.Checked = _currentEditorEx.WhitespaceSpacesVisible;
            viewShowNewLineMenuItem.Checked = _currentEditorEx.WhitespaceLineEndsVisible;
            viewMarkLineModificationsMenuItem.Checked = _currentEditorEx.Document.LineModificationMarkingEnabled;
            viewhHighlightCurrentLineMenuItem.Checked = _currentEditorEx.CurrentLineHighlightingVisible;
            viewShowColumn80GuideMenuItem.Checked = !viewShowColumn80GuideMenuItem.Checked;
            //menuBracketMatchingStyle.Checked = _editorSettings.BracketMatchingStyle == BracketMatchingStyle.After;
            //menuEnableVirtualSpace.Checked = _editorSettings.AllowCaretBeyondEOL;
            //menuShowLineNumbers.Checked = _editorSettings.ShowLineNumbers;
        }

        #endregion

        #region Tools Menu And Toolbar Methods.

        private void EditStandardValues()
        {
            if (!_currentEditorEx.Document.HasContent)
                return;

            _xDocument = XDocument.Parse(_currentEditorEx.Text, LoadOptions.PreserveWhitespace);

            FormEditStandardValues frm = new FormEditStandardValues(_xDocument);

            if (frm.ShowDialog(this) == DialogResult.OK)
            {
                StringBuilder output = new StringBuilder();

                XDocument xml = frm.GetXDocument;

                output.AppendLine(_xDeclaration.ToString());
                output.Append(xml.ToString());

                _currentEditorEx.Document.Text = output.ToString();
            }
        }

        private void EditUserDefinedValues()
        {
            if (!_currentEditorEx.Document.HasContent)
                return;

            if(_railWorksPath == Railworkspath)
            {
                const string message = "The path to the railworks folder is not set! Please set the path before start working on user defined values.\n\n" +
                                       "Would you like to set the path now?";

                if(MessageBox.Show(this, message, MsgBoxName, MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)
                {
                    SetRailWorksPath();
                }
                else
                {
                    return;
                }
            }

            _xDocument = XDocument.Parse(_currentEditorEx.Text, LoadOptions.PreserveWhitespace);

            FormEditUserValues frm = new FormEditUserValues(_xDocument, _railWorksPath);

            if (frm.ShowDialog(this) == DialogResult.OK)
            {
                StringBuilder output = new StringBuilder();

                XDocument xml = frm.GetXDocument;

                output.AppendLine(_xDeclaration.ToString());
                output.Append(xml.ToString());

                _currentEditorEx.Document.Text = output.ToString();
            }
        }

        private void EditSettings()
        {
            if (!_currentEditorEx.Document.HasContent)
                return;

            if (_railWorksPath == Railworkspath)
            {
                const string message = "The path to the railworks folder is not set! Please set the path before start working on user settings.\n\n" +
                                       "Would you like to set the path now?";

                if (MessageBox.Show(this, message, MsgBoxName, MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)
                {
                    SetRailWorksPath();
                }
                else
                {
                    return;
                }
            }

            _xDocument = XDocument.Parse(_currentEditorEx.Text, LoadOptions.PreserveWhitespace);

            FormEditSettings frm = new FormEditSettings(_xDocument, _railWorksPath);

            if (frm.ShowDialog(this) == DialogResult.OK)
            {
                //
            }
        }

        private void EditUicCargoWaggonNUmber()
        {
            if (!_currentEditorEx.Document.HasContent)
                return;

            if (_railWorksPath == Railworkspath)
            {
                const string message = "The path to the railworks folder is not set! Please set the path before start working on user settings.\n\n" +
                                       "Would you like to set the path now?";

                if (MessageBox.Show(this, message, MsgBoxName, MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)
                {
                    SetRailWorksPath();
                }
                else
                {
                    return;
                }
            }

            _xDocument = XDocument.Parse(_currentEditorEx.Text, LoadOptions.PreserveWhitespace);

            FormEditUicCargoNumbers frm = new FormEditUicCargoNumbers(_xDocument, _railWorksPath);

            if (frm.ShowDialog(this) == DialogResult.OK)
            {
                StringBuilder output = new StringBuilder();

                XDocument xml = frm.GetXDocument;

                output.AppendLine(_xDeclaration.ToString());
                output.Append(xml.ToString());

                _currentEditorEx.Document.Text = output.ToString();
            }
        }

        private void RunMacro()
        {
            _currentEditorEx.SelectedView.RaiseEditCommand(new RunMacroCommand());
        }

        private void RecordMacro()
        {
            _currentEditorEx.SelectedView.RaiseEditCommand(new ToggleMacroRecordingCommand());
        }

        private void PauseMacro()
        {
            _currentEditorEx.SelectedView.RaiseEditCommand(new PauseResumeMacroRecordingCommand());
        }

        private void CancelMacro()
        {
            _currentEditorEx.SelectedView.RaiseEditCommand(new CancelMacroRecordingCommand());
        }

        private void ShowTextStatistics()
        {
            if (_currentEditorEx.SelectedView.Selection.Length > 0)
                _currentEditorEx.SelectedView.GetTextStatisticsForSelectedText().Show(this, "Selected Text Statistics");
            else
                _currentEditorEx.Document.GetTextStatistics().Show(this, "Document Statistics");
        }

        #endregion

        #region Help Menu And Toolbar Methods.

        private void ShowAbout()
        {
            FormAbout frm = new FormAbout();

            frm.ShowDialog(this);
        }

        #endregion

        #region Event Implementation.

        //private void findReplaceForm_StatusChanged(object sender, FindReplaceStatusChangeEventArgs e)
        //{
        //    switch (e.ChangeType)
        //    {
        //        case FindReplaceStatusChangeType.Find:
        //            //this.SetStatusMessage("Find: \"" + e.Options.FindText + "\"");
        //            break;
        //        case FindReplaceStatusChangeType.PastDocumentEnd:
        //            //this.SetStatusMessage("Past the end of the document");
        //            break;
        //        case FindReplaceStatusChangeType.Ready:
        //            //this.SetStatusMessage("Ready");
        //            break;
        //        case FindReplaceStatusChangeType.Replace:
        //            //this.SetStatusMessage("Replace: \"" + e.Options.FindText + "\", with: \"" + e.Options.ReplaceText + "\"");
        //            break;
        //    }
        //}

        private void OnMacroRecordingStateChanged(object sender, EventArgs e)
        {
            switch (_currentEditorEx.MacroRecording.State)
            {
                case MacroRecordingState.Recording:
                    tsbRunMacro.Enabled = false;
                    tsbRecordMacro.ImageIndex = 1;  // Stop button
                    toolsRecordMacroMenuItem.Image = imlMenu.Images[1];
                    tsbRecordMacro.ToolTipText = @"Stop Recording";
                    tsbPauseMacro.Enabled = true;
                    tsbPauseMacro.Checked = false;
                    tsbPauseMacro.ToolTipText = @"Pause Recording";
                    tsbCancelMacro.Enabled = true;
                    break;
                case MacroRecordingState.Paused:
                    tsbPauseMacro.Checked = true;
                    tsbPauseMacro.ToolTipText = @"Resume Recording";
                    break;
                default:
                    tsbRunMacro.Enabled = (_currentEditorEx.MacroRecording.LastMacroCommand != null);
                    tsbRecordMacro.ImageIndex = 0;  // Record button
                    toolsRecordMacroMenuItem.Image = imlMenu.Images[0];;
                    tsbRecordMacro.ToolTipText = @"Record Macro";
                    tsbPauseMacro.Enabled = false;
                    tsbPauseMacro.Checked = false;
                    tsbPauseMacro.ToolTipText = @"Pause Recording";
                    tsbCancelMacro.Enabled = false;
                    break;
            }

            toolsRunMacroMenuItem.Enabled = tsbRunMacro.Enabled;
            toolsRecordMacroMenuItem.Text = tsbRecordMacro.ToolTipText;
            toolsPauseMacroMenuItem.Enabled = tsbPauseMacro.Enabled;
            toolsPauseMacroMenuItem.Text = tsbPauseMacro.ToolTipText;
            toolsCancelRecordingMenuItem.Enabled = tsbCancelMacro.Enabled;
        }

        private void OnChangeAttributesEvent(object sender, FileSystemEventArgs e)
        {
            if(_currentEditorEx != null)
            {
                if (Functions.IsFileReadOnly(_currentEditorEx.ExtendedInfo.Path))
                {
                    statusLabelPath.ForeColor = Color.Red;
                }
                else
                {
                    statusLabelPath.ForeColor = Color.DarkGreen;
                } 
            }
            else
            {
                statusLabelPath.ForeColor = Color.Black;
            }
        }

        private void OnOverwriteModeChanged(object sender, EventArgs e)
        {
            SetWriteType();
        }

        private void UndoRedoStateChanged(object sender, UndoRedoStateChangedEventArgs e)
        {
            SetUndoRedoStatus(e.Document.UndoRedo.CanUndo, e.Document.UndoRedo.CanRedo);
        }

        private void OnDocumentTextChanged(object sender, DocumentModificationEventArgs e)
        {
            _currentEditorEx.Document.Modified = true;

            SetDocumentInfo(_currentEditorEx.Document.Length, _currentEditorEx.Document.Lines.Count);

            SetSaveStatus(_currentEditorEx.Document.Modified);
        }

        private void OnDocumentModifiedChanged(object sender, EventArgs e)
        {
            SetDocumentSaveStatus(_currentEditorEx.Document.Modified);
        }

        private void OnSelectionChanged(object sender, SelectionEventArgs e)
        {
            DocumentPosition pos =  _currentEditorEx.Caret.DisplayDocumentPosition;

            int position = _currentEditorEx.Caret.Offset;

            SetPositionInfo(pos.Line, pos.Character, position);

            SetSelectionInfo(_currentEditorEx.SelectedView.Selection.Length);
        }

        #endregion

        #region Helper Methods.

        private bool IsFileOpened(string path)
        {
            return sandDockManager.GetDockControls().Select(dctrl => (SyntaxEditorEx) dctrl.Controls[0]).Any(se => se.ExtendedInfo.Path == path);
        }

        private void InitNewSyntaxEditor(SyntaxEditorEx syntaxEditorEx)
        {
            syntaxEditorEx.Document.LineModificationMarkingEnabled = true;
            viewMarkLineModificationsMenuItem.Checked = true;

            syntaxEditorEx.Font = new Font("Consolas", 10);
            syntaxEditorEx.LineNumberMarginFont = new Font("Consolas", 10);
            syntaxEditorEx.PrintSettings.PrintDocument.DefaultPageSettings.Landscape = true;

            statusLabelMode.Text = syntaxEditorEx.OverwriteMode ? @"OVR" : @"INS";
        }

        private void ConnectNewSyntaxEditor()
        {
            _currentEditorEx.OverwriteModeChanged += (OnOverwriteModeChanged);
            _currentEditorEx.MacroRecordingStateChanged += (OnMacroRecordingStateChanged);
            _currentEditorEx.SelectionChanged += (OnSelectionChanged);
            _currentEditorEx.DocumentModifiedChanged += (OnDocumentModifiedChanged);
            _currentEditorEx.DocumentTextChanged += (OnDocumentTextChanged);
            _currentEditorEx.Document.UndoRedoStateChanged += (UndoRedoStateChanged);

            viewMarkLineModificationsMenuItem.Checked = _currentEditorEx.Document.LineModificationMarkingEnabled;

            SetWriteType();
        }

        private void DisconnectSyntaxEditor()
        {
            _currentEditorEx.OverwriteModeChanged -= (OnOverwriteModeChanged);
            _currentEditorEx.MacroRecordingStateChanged -= (OnMacroRecordingStateChanged);
            _currentEditorEx.SelectionChanged -= (OnSelectionChanged);
            _currentEditorEx.DocumentModifiedChanged -= (OnDocumentModifiedChanged);
            _currentEditorEx.DocumentTextChanged -= (OnDocumentTextChanged);
            _currentEditorEx.Document.UndoRedoStateChanged -= (UndoRedoStateChanged);
        }

        private void InitForm()
        {
            _resourceManager = new ResourceManager("RWXMLEdit.Client.Properties.Resources", GetType().Assembly);

            fileSystemWatcher.Changed += (OnChangeAttributesEvent);

            HasClipboardText();

            Text = _winName;

            fileSystemWatcher.EnableRaisingEvents = false;
            fileSystemWatcher.NotifyFilter = NotifyFilters.Attributes;
            fileSystemWatcher.Filter = "*.xml";

            EnableDisableToolBar(false);

            EnableDisableMenu(false);
        }

        private static void SetWaitCursor(bool isWaitCursor)
        {
            if(isWaitCursor)
                Cursor.Current = Cursors.WaitCursor;
            else
                Cursor.Current = Cursors.Default;
        }

        private void SetWriteType()
        {
            if(_currentEditorEx.OverwriteMode)
            {
                statusLabelMode.Text = @"OVR";
            }
            else
            {
                statusLabelMode.Text = @"INS";
            }
        }

        private void SetDocumentSaveStatus(bool isModified)
        {
            if (!_currentEditorEx.Document.HasContent)
                return;

            if (this.Disposing)
                return;

            if (isModified)
            {
                if (!Text.EndsWith("*"))
                {
                    Text += @" *";
                }
                 
                sandDockManager.ActiveTabbedDocument.TabImage = imlTabs.Images[1];
            }
            else
            {
                if (Text.EndsWith("*"))
                {
                    Text = Text.Substring(0, Text.Length - 2);
                }

                sandDockManager.ActiveTabbedDocument.TabImage = imlTabs.Images[0];
            }

            SyntaxEditorEx editor = (SyntaxEditorEx) sandDockManager.ActiveTabbedDocument.Controls[0];

            if(Functions.IsFileReadOnly(editor.ExtendedInfo.Path))    
            {
                sandDockManager.ActiveTabbedDocument.TabImage = imlTabs.Images[2];
            }
        }

        private static string GetPrintingDocumentName(string viewName)
        {
            string docName;

            if (string.IsNullOrEmpty(viewName))
            {
                docName = "RailWorks XML Settings - No Name";
            }
            else
            {
                docName = string.Format("RW XML Settings - {0}", viewName);
            }

            return docName;
        }

        private void HasClipboardText()
        {
            if (Clipboard.ContainsText(TextDataFormat.UnicodeText) || Clipboard.ContainsText(TextDataFormat.Text))
            {
                tsbPaste.Enabled = true;
                editPasteMenuItem.Enabled = true;
                editCopyAppendMenuItem.Enabled = true;
                editCutAppendMenuItem.Enabled = true;
                editClearClipboardMenuItem.Enabled = true;
                pasteCtxMenuItem.Enabled = true;
            }
            else
            {
                tsbPaste.Enabled = false;
                editPasteMenuItem.Enabled = false;
                editCopyAppendMenuItem.Enabled = false;
                editCutAppendMenuItem.Enabled = false;
                editClearClipboardMenuItem.Enabled = false;
                pasteCtxMenuItem.Enabled = false;
            }
        }

        private void SetEditorFileInfo(string text)
        {
            if (string.IsNullOrEmpty(text))
            {
                statusLabelPath.Text = @"No XML-file open for edit";
                statusLabelEncoding.Text = @"Encoding :";
            }
            else
            {
                statusLabelPath.Text = text;
                statusLabelEncoding.Text = string.Format("Encoding : {0}", Encoding.UTF8.EncodingName);
            }
        }

        private void ResetStatusbar()
        {
            statusLabelLength.Text = @"Length : ";
            statusLabelLines.Text = @"Lines : ";
            statusLabelLine.Text = @"Ln : ";
            statusLabelCol.Text = @"Col : ";
            statusLabelPos.Text = @"Pos : ";
            statusLabelSel.Text = @"Sel : ";
        }

        private void SetDocumentInfo(int length, int lines)
        {
            statusLabelLength.Text = string.Format("Length : {0:# ##0}", length);
            statusLabelLines.Text = string.Format("Lines : {0:# ##0}", lines);
        }

        private void SetPositionInfo(int line, int col, int pos)
        {
            statusLabelLine.Text = string.Format("Ln : {0:# ##0}", line);
            statusLabelCol.Text = string.Format("Col : {0:# ##0}", col);
            statusLabelPos.Text = string.Format("Pos : {0:# ##0}", pos);
        }

        private void SetSelectionInfo(int selection)
        {
            statusLabelSel.Text = string.Format("Sel : {0:# ##0}", selection);
        }

        private void SetSaveStatus(bool canSave)
        {
            tsbSave.Enabled = canSave;
            tsbSaveAllXmlFiles.Enabled = canSave;
            fileSaveMenuItem.Enabled = canSave;
            fileSaveAllMenuItem.Enabled = canSave;

            if(sandDockManager.GetDockControls().Length > 1)
            {
                bool hasNotSavedDocuments = false;

                foreach (DockControl dc in sandDockManager.GetDockControls())
                {
                    SyntaxEditorEx editor = (SyntaxEditorEx) dc.Controls[0];

                    if(editor.Document.Modified && !Functions.IsFileReadOnly(editor.ExtendedInfo.Path))
                    {
                        hasNotSavedDocuments = true;
                        break;
                    }
                }

                tsbSaveAllXmlFiles.Enabled = hasNotSavedDocuments;

                fileSaveAllMenuItem.Enabled = hasNotSavedDocuments;
            }
        }

        private void SetCloseStatus(bool canClose)
        {
            tsbClose.Enabled = canClose;
            tsbCloseAll.Enabled = canClose;
            fileCloseMenuItem.Enabled = canClose;
            fileCloseAllMenuItem.Enabled = canClose;
            fileCloseAllButActiveMenuItem.Enabled = canClose;
        }

        private void RefreshUndoRedoStatus(bool undo, bool redo)
        {
            editUndoMenuItem.Enabled = undo;
            editRedoMenuItem.Enabled = redo;

            tsbUndo.Enabled = undo;
            tsbRedo.Enabled = redo;
        }

        private void SetUndoRedoStatus(bool undo, bool redo)
        {
            editUndoMenuItem.Enabled = undo;
            editRedoMenuItem.Enabled = redo;

            tsbUndo.Enabled = undo;
            tsbRedo.Enabled = redo;

            if(!undo)
            {
                SetSaveStatus(false);
                SetDocumentSaveStatus(false);
                _currentEditorEx.Document.Modified = false;
            }
            else
            {
                SetSaveStatus(true);
                SetDocumentSaveStatus(true);
                _currentEditorEx.Document.Modified = true;
            }
        }

        private void ResetEditor()
        {
            statusLabelPath.ForeColor = Color.Black;

            Text = _winName;

            SetSaveStatus(false);

            RefreshUndoRedoStatus(false, false);
        }

        private void SetRailWorksPath()
        {
            folderBrowserDialog = new FolderBrowserDialog();

            folderBrowserDialog.Description = @"Select path to the RailWorks folder.";

            DialogResult folder = folderBrowserDialog.ShowDialog(this);

            if (folder == DialogResult.OK)
            {
                string testPath = Path.Combine(folderBrowserDialog.SelectedPath, "RailWorks.exe");

                if (!File.Exists(testPath))
                {
                    string message = string.Format("The RailWorks folder should contain the file (RailWorks.exe)!\n\n" +
                    "This directory does not contain (RailWorks.exe). Please try again and find the correct railworks directory");

                    MessageBox.Show(this, message, MsgBoxName, MessageBoxButtons.OK, MessageBoxIcon.Warning);

                    return;
                }

                _railWorksPath = folderBrowserDialog.SelectedPath;

                Properties.Settings.Default.RailWorksPath = _railWorksPath;

                llbRailWorksPath.Links[0].LinkData = _railWorksPath;

                llbRailWorksPath.Text = _railWorksPath;
            }
        }

        private void EnableDisableToolBar(bool enable)
        {
            tsbPreview.Enabled = enable;
            tsbPrint.Enabled = enable;
            tsbCut.Enabled = enable;
            tsbCopy.Enabled = enable;
            tsbPaste.Enabled = enable;
            tsbFindReplace.Enabled = enable;
            tsbGoTo.Enabled = enable;
            tsbIncreaseIndendt.Enabled = enable;
            tsbDecreaseLineIndent.Enabled = enable;
            tsbCommentSelection.Enabled = enable;
            tsbUncommentSelection.Enabled = enable;
            tsbToggleBookmark.Enabled = enable;
            tsbPreviousBookmark.Enabled = enable;
            tsbNextBookmark.Enabled = enable;
            tsbClearBookmarks.Enabled = enable;
            tsbRunMacro.Enabled = false;
            tsbRecordMacro.Enabled = enable;
            tsbPauseMacro.Enabled = false;
            tsbCancelMacro.Enabled = false;

            if (enable)
            {
                tsbRecordMacro.Image = imlMenu.Images[0];
            }
        }

        private void EnableDisableMenu(bool enable)
        {
            fileSaveAsMenuItem.Enabled = enable;
            fileSaveAsHTMLMenuItem.Enabled = enable;
            fileSaveAsRTFMenuItem.Enabled = enable;
            fileBackupMenuItem.Enabled = enable;
            filePageSetupMenuItem.Enabled = enable;
            filePrintPreviewMenuItem.Enabled = enable;
            filePrintMenuItem.Enabled = enable;
            filePrintNowMenuItem.Enabled = enable;

            //toolsEditStandardAttributeMenuItem.Enabled = enable;
            //toolsEditUserDefinedAttributesMenuItem.Enabled = enable;
            //toolsMacroMenuItem.Enabled = enable;
            //toolsTextStatisticsMenuItem.Enabled = enable;

            mainEditMenuItem.Visible = enable;
            mainFormatMenuItem.Visible = enable;
            mainViewMenuItem.Visible = enable;
            mainToolsMenuItem.Visible = enable;
            mainWindowMenuItem.Visible = enable;

            if (enable)
            {
                toolsRecordMacroMenuItem.Image = imlMenu.Images[0];
            }
        }

        #endregion

        #region Context Menu Events.

        private void cutCtxMenuItem_Click(object sender, EventArgs e)
        {
            Cut();
        }

        private void copyCtxMenuItem_Click(object sender, EventArgs e)
        {
            Copy();
        }

        private void pasteCtxMenuItem_Click(object sender, EventArgs e)
        {
            Paste();
        }

        private void deleteCtxMenuItem_Click(object sender, EventArgs e)
        {
            Delete();
        }

        private void selectAllCtxMenuItem_Click(object sender, EventArgs e)
        {
            SelectAll();
        }

        private void selectLineCtxMenuItem_Click(object sender, EventArgs e)
        {
            SelectLine();
        }

        private void selectNoneCtxMenuItem_Click(object sender, EventArgs e)
        {
            SelectNone();
        }

        private void selectUppercaseCtxMenuItem_Click(object sender, EventArgs e)
        {
            MakeUppercase();
        }

        private void makeLowercaseCtxMenuItem_Click(object sender, EventArgs e)
        {
            MakeLowercase();
        }

        private void changePathCtxMenuItem_Click(object sender, EventArgs e)
        {
            SetRailWorksPath();
        }

        private void deletePathCtxMenuItem_Click(object sender, EventArgs e)
        {
            _railWorksPath = Railworkspath;

            Properties.Settings.Default.RailWorksPath = _railWorksPath;

            llbRailWorksPath.Links[0].LinkData = _railWorksPath;

            llbRailWorksPath.Text = _railWorksPath;
        }

        #endregion

        #region Toolbar Events.

        private void tsbOpen_Click(object sender, EventArgs e)
        {
            OpenXmlFile();
        }

        private void tsbSave_Click(object sender, EventArgs e)
        {
            SaveXmlFile();
        }

        private void tsbSaveAllXmlFiles_Click(object sender, EventArgs e)
        {
            SaveAllXmlFiles();
        }

        private void tsbClose_Click(object sender, EventArgs e)
        {
            CloseXmlFile();
        }

        private void tsbCloseAll_Click(object sender, EventArgs e)
        {
            CloseAllXmlFiles(false);
        }

        private void tsbPreview_Click(object sender, EventArgs e)
        {
            PrintPreview();
        }

        private void tsbPrint_Click(object sender, EventArgs e)
        {
            Print();
        }

        private void tsbUndo_Click(object sender, EventArgs e)
        {
            Undo();
        }

        private void tsbRedo_Click(object sender, EventArgs e)
        {
            Redo();
        }

        private void tsbCut_Click(object sender, EventArgs e)
        {
            Cut();
        }

        private void tsbCopy_Click(object sender, EventArgs e)
        {
            Copy();
        }

        private void tsbPaste_Click(object sender, EventArgs e)
        {
            Paste();
        }

        private void tsbFindReplace_Click(object sender, EventArgs e)
        {
            ShowFindAndReplace();
        }

        private void tsbGoTo_Click(object sender, EventArgs e)
        {
            ShowGoTo();
        }

        private void tsbIncreaseIndendt_Click(object sender, EventArgs e)
        {
            IncreaseIndent();
        }

        private void tsbDecreaseLineIndent_Click(object sender, EventArgs e)
        {
            DecreaseIndent();
        }

        private void tsbCommentSelection_Click(object sender, EventArgs e)
        {
            CommentSelection();
        }

        private void tsbUncommentSelection_Click(object sender, EventArgs e)
        {
            UncommentSelection();
        }

        private void tsbToggleBookmark_Click(object sender, EventArgs e)
        {
            ToggleBookmark();
        }

        private void tsbPreviousBookmark_Click(object sender, EventArgs e)
        {
            GoToPreviousBookmark();
        }

        private void tsbNextBookmark_Click(object sender, EventArgs e)
        {
            GoToNextBookmark();
        }

        private void tsbClearBookmarks_Click(object sender, EventArgs e)
        {
            ClearBookmarks();
        }

        private void tsbRunMacro_Click(object sender, EventArgs e)
        {
            RunMacro();
        }

        private void tsbRecordMacro_Click(object sender, EventArgs e)
        {
            RecordMacro();
        }

        private void tsbPauseMacro_Click(object sender, EventArgs e)
        {
            PauseMacro();
        }

        private void tsbCancelMacro_Click(object sender, EventArgs e)
        {
            CancelMacro();
        }

        #endregion

        #region File Menu Events.

        private void fileOpenMenuItem_Click(object sender, EventArgs e)
        {
            OpenXmlFile();
        }

        private void fileSaveMenuItem_Click(object sender, EventArgs e)
        {
            if (_currentEditorEx.Document.Modified)
            {
                SaveXmlFile();
            }
        }

        private void fileSaveAllMenuItem_Click(object sender, EventArgs e)
        {
            SaveAllXmlFiles();
        }

        private void fileSaveAsMenuItem_Click(object sender, EventArgs e)
        {
            SaveXmlFileAs();
        }

        private void fileSaveAsHTMLMenuItem_Click(object sender, EventArgs e)
        {
            SaveAsHtml();
        }

        private void fileSaveAsRTFMenuItem_Click(object sender, EventArgs e)
        {
            SaveAsRtf();
        }

        private void fileCloseMenuItem_Click(object sender, EventArgs e)
        {
            CloseXmlFile();
        }

        private void fileCloseAllMenuItem_Click(object sender, EventArgs e)
        {
            CloseAllXmlFiles(false);
        }

        private void fileCloseAllButActiveMenuItem_Click(object sender, EventArgs e)
        {
            CloseAllXmlFiles(true);
        }

        private void fileBackupMenuItem_Click(object sender, EventArgs e)
        {
            BackupXmlFile();
        }

        private void filePageSetupMenuItem_Click(object sender, EventArgs e)
        {
            PageSetup();
        }

        private void filePrintPreviewMenuItem_Click(object sender, EventArgs e)
        {
            PrintPreview();
        }

        private void filePrintMenuItem_Click(object sender, EventArgs e)
        {
            Print();
        }

        private void filePrintNowMenuItem_Click(object sender, EventArgs e)
        {
            PrintNow();
        }

        private void fileExitMenuItem_Click(object sender, EventArgs e)
        {
            Close();
        }

        #endregion

        #region Edit Menu Events.

        private void editUndoMenuItem_Click(object sender, EventArgs e)
        {
            Undo();
        }

        private void editRedoMenuItem_Click(object sender, EventArgs e)
        {
            Redo();
        }

        private void editCutMenuItem_Click(object sender, EventArgs e)
        {
            Cut();
        }

        private void editCopyMenuItem_Click(object sender, EventArgs e)
        {
            Copy();
        }

        private void editCutAppendMenuItem_Click(object sender, EventArgs e)
        {
            CutAndAppend();
        }

        private void editCopyAppendMenuItem_Click(object sender, EventArgs e)
        {
            CopyAndAppend();
        }

        private void editClearClipboardMenuItem_Click(object sender, EventArgs e)
        {
            ClearClipboard();
        }

        private void editPasteMenuItem_Click(object sender, EventArgs e)
        {
            Paste();
        }

        private void editDeleteMenuItem_Click(object sender, EventArgs e)
        {
            Delete();
        }

        private void editSelectAllMenuItem_Click(object sender, EventArgs e)
        {
            SelectAll();
        }

        private void editSelectLineMenuItem_Click(object sender, EventArgs e)
        {
            SelectLine();
        }

        private void editSelectWordMenuItem_Click(object sender, EventArgs e)
        {
            SelectWord();
        }

        private void editSelectNoneMenuItem_Click(object sender, EventArgs e)
        {
            SelectNone();
        }

        private void editToggleMenuItem_Click(object sender, EventArgs e)
        {
            ToggleBookmark();
        }

        private void editEnableBookmarkMenuItem_Click(object sender, EventArgs e)
        {
            EnableBookmark();
        }

        private void editEnableAllBookmarksMenuItem_Click(object sender, EventArgs e)
        {
            EnableAllBookmarks();
        }

        private void editPreviousBookmarkMenuItem_Click(object sender, EventArgs e)
        {
            GoToPreviousBookmark();
        }

        private void editNextBookmarkMenuItem_Click(object sender, EventArgs e)
        {
            GoToNextBookmark();
        }

        private void editClearBookmarksMenuItem_Click(object sender, EventArgs e)
        {
            ClearBookmarks();
        }

        private void editCommentSelectionMenuItem_Click(object sender, EventArgs e)
        {
            CommentSelection();
        }

        private void editUncommentSelectionMenuItem_Click(object sender, EventArgs e)
        {
            UncommentSelection();
        }

        private void editGotoMenuItem_Click(object sender, EventArgs e)
        {
            ShowGoTo();
        }

        private void editFindAndReplaceMenuItem_Click(object sender, EventArgs e)
        {
            ShowFindAndReplace();
        }

        #endregion

        #region Format Menu Events.

        private void formatMakeUppercaseMenuItem_Click(object sender, EventArgs e)
        {
            MakeUppercase();
        }

        private void formatMakeLowercaseMenuItem_Click(object sender, EventArgs e)
        {
            MakeLowercase();
        }

        private void formatCapitalizeMenuItem_Click(object sender, EventArgs e)
        {
            Capitalize();
        }

        private void formatInvertCasingMenuItem_Click(object sender, EventArgs e)
        {
            InvertCaseing();
        }

        private void formatIncreaseLineIndentMenuItem_Click(object sender, EventArgs e)
        {
            IncreaseIndent();
        }

        private void formatDecreaseLineIndentMenuItem_Click(object sender, EventArgs e)
        {
            DecreaseIndent();
        }

        private void formatConvertTabsToSpacesMenuItem_Click(object sender, EventArgs e)
        {
            ConvertTabsToSpaces();
        }

        private void formatConvertSpacesToTabsMenuItem_Click(object sender, EventArgs e)
        {
            ConvertSpacesToTabs();
        }

        private void formatTabifySelectedLinesMenuItem_Click(object sender, EventArgs e)
        {
            TabifySelection();
        }

        private void formatUntabifySelectedLinesMenuItem_Click(object sender, EventArgs e)
        {
            UntabifySelection();
        }

        private void formatTrimTrailingWhitespaceMenuItem_Click(object sender, EventArgs e)
        {
            TrimTrailingWhitespace();
        }

        private void formatDeleteHorizontalWhitespaceMenuItem_Click(object sender, EventArgs e)
        {
            _currentEditorEx.SelectedView.DeleteHorizontalWhitespace();
        }

        private void formatDeleteLineMenuItem_Click(object sender, EventArgs e)
        {
            _currentEditorEx.SelectedView.DeleteLine();
        }

        private void formatDuplicateLineMenuItem_Click(object sender, EventArgs e)
        {
            _currentEditorEx.SelectedView.DuplicateLine();
        }

        private void formatDeleteBlankLinesMenuItem_Click(object sender, EventArgs e)
        {
            _currentEditorEx.SelectedView.DeleteBlankLines();
        }

        private void formatTransposeLinesMenuItem_Click(object sender, EventArgs e)
        {
            _currentEditorEx.SelectedView.TransposeLines();
        }

        private void formatTransposeWordsMenuItem_Click(object sender, EventArgs e)
        {
            _currentEditorEx.SelectedView.TransposeWords();
        }

        #endregion

        #region View Menu Events.

        private void viewShowSpacesTabsMenuItem_Click(object sender, EventArgs e)
        {
            _currentEditorEx.WhitespaceSpacesVisible = _currentEditorEx.WhitespaceTabsVisible = !_currentEditorEx.WhitespaceSpacesVisible;
            OnSettingsChanged();
        }

        private void viewShowNewLineMenuItem_Click(object sender, EventArgs e)
        {
            _currentEditorEx.WhitespaceLineEndsVisible = !_currentEditorEx.WhitespaceLineEndsVisible;
            OnSettingsChanged();
        }

        private void viewMarkLineModificationsMenuItem_Click(object sender, EventArgs e)
        {
            _currentEditorEx.Document.LineModificationMarkingEnabled = !_currentEditorEx.Document.LineModificationMarkingEnabled;
            OnSettingsChanged();
        }

        private void viewhHighlightCurrentLineMenuItem_Click(object sender, EventArgs e)
        {
            _currentEditorEx.CurrentLineHighlightingVisible = !_currentEditorEx.CurrentLineHighlightingVisible;
            OnSettingsChanged();
        }

        #endregion

        #region Tools Menu Events.

        private void toolsEditFrontCouplingPivotMenuItem_Click(object sender, EventArgs e)
        {
            EditStandardValues();
        }

        private void toolsEditUserDefinedAttributesMenuItem_Click(object sender, EventArgs e)
        {
            EditUserDefinedValues();
        }

        private void toolsRunMacroMenuItem_Click(object sender, EventArgs e)
        {
            RunMacro();
        }

        private void toolsRecordMacroMenuItem1_Click(object sender, EventArgs e)
        {
            RecordMacro();
        }

        private void toolsPauseMacroMenuItem_Click(object sender, EventArgs e)
        {
            PauseMacro();
        }

        private void toolsCancelRecordingMenuItem_Click(object sender, EventArgs e)
        {
            CancelMacro();
        }

        private void toolsTextStatisticsMenuItem_Click(object sender, EventArgs e)
        {
            ShowTextStatistics();
        }

        #endregion

        #region Window Menu Events.

        private void windowSplitVerticalMenuItem_Click_1(object sender, EventArgs e)
        {
            _currentEditorEx.HasHorizontalSplit = false;
            _currentEditorEx.HasVerticalSplit = true;
        }

        private void windowSplitHorizontalMenuItem_Click(object sender, EventArgs e)
        {
            _currentEditorEx.HasHorizontalSplit = true;
            _currentEditorEx.HasVerticalSplit = false;
        }

        private void windowSplitFourwayMenuItem_Click(object sender, EventArgs e)
        {
            _currentEditorEx.HasHorizontalSplit = true;
            _currentEditorEx.HasVerticalSplit = true;
        }

        private void windowNoSplitMenuItem_Click(object sender, EventArgs e)
        {
            _currentEditorEx.HasHorizontalSplit = false;
            _currentEditorEx.HasVerticalSplit = false;
        }

        #endregion

        #region Help Menu Events.

        private void helpAboutMenuItem_Click(object sender, EventArgs e)
        {
            ShowAbout();
        }

        #endregion

        private void toolsEditSettingsMenuItem_Click(object sender, EventArgs e)
        {
            EditSettings();
        }

        private void toolsUICCargoMenuItem_Click(object sender, EventArgs e)
        {
            EditUicCargoWaggonNUmber();
        }

        #region Commented Code.

        //private void syntaxEditor_DragDrop(object sender, DragEventArgs e)
        //{
        //    syntaxEditor.Document.ReadOnly = false;
        //}

        //private void syntaxEditor_PasteDragDrop(object sender, PasteDragDropEventArgs e)
        //{
        //    if (e.DataObject.GetDataPresent(DataFormats.FileDrop))
        //    {
        //        object files = e.DataObject.GetData(DataFormats.FileDrop);
        //        if ((files is string[]) && (((string[])files).Length > 0))
        //        {
        //            string filename = ((string[])files)[0];

        //            switch (e.Source)
        //            {
        //                case PasteDragDropSource.DragEnter:
        //                    // If the file exists, pass any non-null string back to tell SyntaxEditor that the dragged file can be dropped
        //                    if (File.Exists(filename))
        //                    {

        //                        e.Text = filename;
        //                    }

        //                    break;
        //                case PasteDragDropSource.DragDrop:
        //                    if (File.Exists(filename))
        //                        OpenXmlFile(filename);
        //                    break;
        //            }
        //        }
        //    }
        //}

        //private void syntaxEditor_DragOver(object sender, DragEventArgs e)
        //{

        //    e.Effect = DragDropEffects.Copy;
        //}

        #endregion
    }
}
